import time
import json
import datetime
from datetime import datetime,timedelta
import requests
import nonebot
from nonebot import on_command, CommandSession

url = 'http://jwgl.sdust.edu.cn/app.do?'
header = {
    'User-Agent': 'Mozilla/5.0 (Linux; U; Mobile; Android 6.0.1;C107-9 Build/FRF91 )',
    'Referer': 'http://www.baidu.com',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'zh-CN,zh-TW;q=0.8,zh;q=0.6,en;q=0.4,ja;q=0.2',
    'cache-control': 'max-age=0'
}
async def login(acount,pwd):
    global login_status,con_state
    number = acount
    pwd = pwd
    params = {
        "method": "authUser",
        "xh": number,
        "pwd": pwd
    }
    i = 0
    while i < 3:
        try:
            session = requests.session()
            req = session.get(url, params=params, timeout=(10,1), headers=header)
            s = json.loads(req.text)
            login_status = s['msg']
            header['token'] = s['token']
            con_state=1
            return session
        except requests.exceptions.RequestException:
            i += 1

def getKbcxAzc(zc):
    #global se
    params = {
        "method": "getKbcxAzc",
        # "xnxqid": s['xnxqh'], 选择学期，默认为当前学期
        "zc": zc,
        "xh": number
    }
    req =se.get(url, params=params, headers=header)
    #print(req.text)
    return req.text

def timeTrans(time):
    index = int((int(time[2]) - 1) / 2)
    icstime = [['080000', '095000'], ['101000', '120000'], ['140000', '155000'], ['161000', '180000'],
                ['190000', '205000']]
    return icstime[index]


async def create_ics():
    global date
    d = {}
    for week in range(1, 21):
        #week = (datetime.now() - datetime(2020, 2, 10)).days // 7 + 1
        # date += timedelta(days=7)
        # print (date)
        #print(week)
        courses = json.loads(getKbcxAzc(week))
        #print(courses)

        for index, course in enumerate(courses):
            if course is None:
                break
            day = (date + timedelta(days=int(course['kcsj'][0]))).strftime('%Y%m%d')
            hour = timeTrans(course['kcsj'])
            kcsj = str(hour[0])[:2] + ':' + str(hour[0])[2:4] + ' ' + str(
                course["kcmc"] + ' ' + str(course['jsmc']) + ' ' + str(course['jsxm']))
            #print(kcsj)
            d.setdefault(day, []).append(kcsj)
        date += timedelta(days=7)
    f = open('c:\\awesome-bot\\awesome\\plugins\\course\\'+qq + '.txt', 'w', encoding='utf-8')
    f.write(str(d))
    f.close()
    #print(d)
    dat = "2020 2 9"
    tmp = dat.split(' ')
    date = datetime(int(tmp[0]), int(tmp[1]), int(tmp[2]))
    return d
#######
dat = "2020 2 9"
tmp = dat.split(' ')
date = datetime(int(tmp[0]), int(tmp[1]), int(tmp[2]))
#######
number="201801020330"
login_status=""
con_state=0
qq=""
@on_command('课表导入')
async def weather(session: CommandSession):
    global number,se,qq
    bot = nonebot.get_bot()
    q=session.ctx['sender']['user_id']
    qq= str(session.ctx['sender']['user_id'])
    number = session.get('number', prompt='你的强智教务账号（20xxxxxxxxxx)是：')
    pwd=session.get('pwd', prompt='你的强智教务密码是：')
    await session.send("正在登陆。。。请等待（登录强智比较慢）")
    se = await login(number, pwd)
    if(con_state==1):
        await session.send("连接成功")
        if(login_status=="登录成功"):
            await session.send(login_status)
            await create_ics()
            with open("C:\\awesome-bot\\awesome\\plugins\\QQ.txt",'a') as f:
                f.write(qq+',')
            await session.send("课表导入成功，已开启每日7点自动推送和课前15分钟提醒！感谢使用")
            await bot.send_private_msg(user_id=1055991127,message="用户+1"+qq)
        else:
            await session.send(login_status)
    else:
        await session.send("连接超时，请稍后再试")
    #await session.send(weather_report)
